<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export'"
            type="danger"
            size="small"
            @click="handleDownload"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'ascending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="照片" width="120px">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态"  prop=""/> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button> -->
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 准备新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <empDialog ref="empDialog" @success="hSuccess" @colse="showDialog=false" />
      </el-dialog>

      <!-- 准备给员工分配权限角色的弹层 -->
      <el-dialog title="分配角色" :visible.sync="roleshowDialog">
        <AssignRole v-if="roleshowDialog" :cur-id="curId" @close="roleshowDialog=false" />
      </el-dialog>

    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import { getEmployees, delEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import empDialog from './empDialog'
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      curId: '', // 保存当前角色的id
      roleshowDialog: false, // 控制分配角色的弹层
      showDialog: false, // 弹出的显示和隐藏
      list: [], // 保存员工列表信息
      total: 0, // 保存数据的总条数
      page: 1, // 页码值
      size: 2 // 每页显示的条数
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 分配角色
    hAssignRole(id) {
      this.curId = id
      this.roleshowDialog = true
    },
    // 加载员工列表信息
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log('getEmployees', res)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
        // 保存数据
      } catch (err) {
        console.log('getEmployees', err)
      }
    },
    // 需求 返回的数据 是正式或非正式
    hireTypeFormat(data) {
      // console.log(employeesEnum.hireType.find(item => item.id === data).value)
      // return employeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 控制页面的条数的切换
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    // 控制页码值的切换
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 重新渲染数据 - 关闭弹出
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    // 删除员工
    hDel(id) {
      this.$confirm('您确认删除该员工吗').then(async() => {
        const res = await delEmployees(id)
        console.log('delEmployees', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployees()
      }).catch(err => err)
    },
    // 定义格式化的函数
    formatData(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      let headers = []
      if (one) {
        // 1.拿到表格的头
        headers = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2.将每个对象中的值存到一个数组中
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    // 导出的回调事件
    async  handleDownload() {
      // 1.发送请求拿到最新的数据
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code !== 10000) return
        // 2.需要获取的到数据转换为Excel需要的格式
        const { headers, data } = this.formatData(res.data.rows)
        // 3.调用 excel.export_json_to_excel 将格式化好的数据写到excel文件中
        import('@/vendor/Export2Excel').then(excel => {
          // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
          // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
          // const list = this.list
          // const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
